//
//  WeatherTableViewController.m
//  ErWa
//
//  Created by 李雪 on 16/3/16.
//  Copyright © 2016年 www.lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "WeatherTableViewController.h"
#import "NewNestHeader.h"

@interface WeatherTableViewController ()<UITableViewDataSource,UITableViewDelegate>

// 城市数组
@property (nonatomic,strong) NSMutableArray * cityArray;
// 添加城市
@property (nonatomic,strong) NSString * addCity;

@end

@implementation WeatherTableViewController

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        NSLog(@"SK = %s",__FUNCTION__);
    }
    return self;
}
- (void)viewWillAppear:(BOOL)animated
{
    
    //解档获取数据
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    //2.拼接地址 (按照什么路径 保存为什么文件) (数组和字典写plist)
    NSString *strpath = [path stringByAppendingPathComponent:@"a.plist"];
    
    NSString *str = [NSKeyedUnarchiver unarchiveObjectWithFile:strpath];
    UIColor *bg = [UIColor colorWithPatternImage:[UIImage imageNamed:str]];
    //     判断当前是什么模式
    BOOL model = [AccountManager sharedInstance].isNight;
    if (model == YES) {
        
        
        self.view.backgroundColor = [UIColor changeColorWithString:@"#a1a3a6"];
        
    } else {
        self.view.backgroundColor = [UIColor clearColor];
        [self.view setBackgroundColor:bg];
        //导航栏按钮颜色
        self.navigationController.navigationBar.tintColor = [UIColor colorWithPatternImage:[UIImage imageNamed:str]];
        //Tabbar按钮颜色
        self.tabBarController.tabBar.tintColor = [UIColor colorWithPatternImage:[UIImage imageNamed:str]];
        
    }
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationItem.title = @"天气预报";
    self.navigationController.navigationBar.translucent = NO;

    
    
    UIBarButtonItem* addButton=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addCitys:)];
    self.navigationItem.rightBarButtonItem = addButton;

    
    self.cityArray = [[NSMutableArray alloc]init];
    [self.cityArray addObject:@"南昌"];
    [self.cityArray addObject:@"宜春"];
    [self.cityArray addObject:@"西安"];
    //保存到NSUserDefaults
    [self saveArray];

    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}



//save data
-(void)saveArray
{
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:self.cityArray forKey:@"city"];
    [defaults synchronize];//同步数据
    [self.tableView reloadData];//更新tableView
}

-(void)addCitys:(UIButton *)sender
{
    NSLog(@"添加城市");
    // alert
    UIAlertController *addAlertControl = [UIAlertController alertControllerWithTitle:@"添加城市" message:@"请输入正确的城市名称" preferredStyle:UIAlertControllerStyleAlert];
    // 取消
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"不添加");
    }];
    // 确定
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if ([[addAlertControl.textFields objectAtIndex:0] isKindOfClass:[UITextField class]]) {
            UITextField *textFields = (UITextField *)[addAlertControl.textFields objectAtIndex:0];
            
            [self.delegate weatherData:textFields.text];
            
            self.addCity = textFields.text;
            [self.cityArray addObject:self.addCity];
            // 刷新数组
            [self saveArray];
        }
    }];
    // 添加
    [addAlertControl addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        
    }];
    [addAlertControl addAction:cancelAction];
    [addAlertControl addAction:okAction];
    [self presentViewController:addAlertControl animated:YES completion:^{
        
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

// 行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.cityArray count];
}

//set cell height
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 添加 cell
    UINib *cellNib = [UINib nibWithNibName:@"cell" bundle:nil];
    [tableView registerNib:cellNib forCellReuseIdentifier:@"mycellxib"];
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"mycellxib" forIndexPath:indexPath];
    
    // 判断cell是否存在/实例对象
    if ([cell isMemberOfClass:[CityWeatherTableViewCell class]]) {
        
        CityWeatherTableViewCell *cityCell = (CityWeatherTableViewCell *)cell;
        cityCell.cityLabel.text = [self.cityArray objectAtIndex:indexPath.row];
        // 添加 获取网络信息 补充url地址
        NSString *url = [NSString stringWithFormat:@"http://wthrcdn.etouch.cn/weather_mini?city=%@",[_cityArray objectAtIndex:indexPath.row]];
        NSLog(@"http://wthrcdn.etouch.cn/weather_mini?city=%@",[_cityArray objectAtIndex:indexPath.row]);
        // 转码
        NSURL *weatherURL = [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        NSURLRequest *URLRequest = [[NSURLRequest alloc]initWithURL:weatherURL];
        NSError *error;
        // 数据
        NSData *weatherData = [NSURLConnection sendSynchronousRequest:URLRequest returningResponse:nil error:&error];
        if (error) {
            NSLog(@"wozaizheli *************** %@",[error localizedDescription]);
        }
        // JSON
        NSDictionary *weatherDataDictionary = [NSJSONSerialization JSONObjectWithData:weatherData options:NSJSONReadingMutableLeaves error:&error];
        if (error) {
            NSLog(@"wokandaol +++++++++++++++ %@",[error localizedDescription]);
        }
        // 数据 key
        NSDictionary *weatherInfoDictionary = [weatherDataDictionary objectForKey:@"data"];
        NSArray *weatherInfoArray = [weatherInfoDictionary objectForKey:@"forecast"];
        NSDictionary *todayWeatherDictionary = [weatherInfoArray objectAtIndex:0];
        NSLog(@"today %@",[todayWeatherDictionary objectForKey:@"type"]);
        
        cityCell.weatherTypeLabel.text = [NSString stringWithFormat:@"%@",[todayWeatherDictionary objectForKey:@"type"]];
        cityCell.weatherInfoLabel.text = [NSString stringWithFormat:@"%@~%@",[todayWeatherDictionary objectForKey:@"high"],[todayWeatherDictionary objectForKey:@"low"]];
        
        //取消点击cell变灰
        [cityCell setSelectionStyle:UITableViewCellSelectionStyleNone];
        
        //     判断当前是什么模式
        BOOL model = [AccountManager sharedInstance].isNight;
        if (model == YES) {
            cityCell.backgroundColor = [UIColor changeColorWithString:@"#a1a3a6"];
        } else {
            cityCell.backgroundColor = [UIColor clearColor];
        }
        
        return cityCell;
        
    }
    
    return cell;
}

//单行选择操作、进行跳转
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //用segue跳转
//    _selectName = [self.cityArray objectAtIndex:indexPath.row];//先找到值、再进入下一行、跳转
//    [self performSegueWithIdentifier:@"showCityWeather" sender:[self.tableView cellForRowAtIndexPath:indexPath]];
    WeatherDetailTableViewController *weatherDetail = [[WeatherDetailTableViewController alloc]init];
    _selectName = [self.cityArray objectAtIndex:indexPath.row];
    weatherDetail.cityName = _cityArray[indexPath.row];
    [self.navigationController pushViewController:weatherDetail animated:YES];
    
}

//侧滑删除
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if(editingStyle == UITableViewCellEditingStyleDelete){
        [self.cityArray removeObjectAtIndex:indexPath.row];
        [self.tableView reloadData];
    }
    if(editingStyle == UITableViewCellEditingStyleInsert){
        NSLog(@"Insert");
    }
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
